package com.maistars.spider.service.parser;

import com.alibaba.fastjson.JSONObject;
import com.maistars.spider.common.constants.ScanType;
import com.maistars.spider.service.domain.rule.SiteRule;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dhr
 * @date 2022/2/3 3:12 下午
 */
public class SiteRuleParser {

    private static final String TML_PREFIX = "$[";

    private static final String TML_POSTFIX = "]";

    public List<String> getRealUrls(SiteRule siteRule) {
        List<String> realUrls = new ArrayList<>();
        JSONObject siteUrlRule = JSONObject.parseObject(siteRule.getSiteRule());
        Integer scanType = siteUrlRule.getInteger("scanType");
        String urlPattern = siteUrlRule.getString("urlPattern");
        if (ScanType.FORCE_TYPE.getValue() == scanType) {
            int start = Integer.parseInt(siteUrlRule.getJSONObject("params").getString("start"));
            int end = Integer.parseInt(siteUrlRule.getJSONObject("params").getString("end"));
            int interval = Integer.parseInt(siteUrlRule.getJSONObject("params").getString("interval"));

            String template = TML_PREFIX + "key" + TML_POSTFIX;

            for (int i = start; i <= end; i = i + interval) {
                realUrls.add(StringUtils.replace(urlPattern, template, i + ""));
            }
        } else if (ScanType.URL_LIST_TYPE.getValue() == scanType) {
            String[] urlArray = urlPattern.split("\n");
            for (String url : urlArray) {
                realUrls.add(url);
            }
        }
        return realUrls;
    }

}
